package searchingtester;

/**
 *
 * @author Seba
 */
public class Search {
    
    private long comparisonCounter;
    
    public int linearSearch(int[] array, int seek){
        comparisonCounter = 0;
        for(int i = 0; i < array.length; i++){
            comparisonCounter++;
            if(array[i] == seek){
                return i;
            }
        }
        return -1;
    }
    
    public int invokeBinarySearch(int[] array, int seek){
        comparisonCounter = 0;
        return binarySearch(array,seek,0,array.length-1);
    }
    
    private int binarySearch(int[] array, int seek, int imin, int imax){
        if(imin > imax){
            return -1;
        } else {
            int mid = (imin+imax)/2;//System.out.println(mid);
            if(array[mid] < seek)
            {
                comparisonCounter++;
                return binarySearch(array,seek,mid+1,imax);
            }
            else if(array[mid] > seek)
            {
                comparisonCounter+=2;
                return binarySearch(array,seek,imin,mid-1);
            }
            else
            {
                comparisonCounter+=2;
                return mid;                
            }
        }
    }

    public long getComparisonCounter() {
        return comparisonCounter;
    }

    public void setComparisonCounter(long comparisonCounter) {
        this.comparisonCounter = comparisonCounter;
    }
}
